<template>
    <div>
        <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
                <span>基本信息</span>
                <div style="float: right;">
                    <el-button size="small" @click="onClose">取 消</el-button>
                    <el-button size="small" type="primary" @click="onFormSubmit">保存</el-button>
                </div>
            </div>
            <form-create v-model="form.fApi" :rule="form.rule" :option="form.option" @btn-pdf-click="uploadPdf" @btn-project-click="projectOpen(true)"/>
            <input type="file" ref="pdfFile" @change="pdfChange" style="display: none;" />
        </el-card>

        <el-dialog :title="project.title" :visible.sync="project.visible" :width="project.width" :close-on-click-modal="false" append-to-body>
            <projectFormList 
            v-if="project.hackReset" 
            :tableData="project.tableData" 
            :tableLabel="project.tableLabel" 
            :models="project"
            @on-search-click="projectOpen"
            @on-check-click="projectCheckSelected"  
            @on-cancel-click="project.visible=false"/>
        </el-dialog>

        <el-dialog :title="supplier.title" :visible.sync="supplier.visible" :width="supplier.width" :close-on-click-modal="false" append-to-body>
            <supplierFormList 
            :key="supplier.keys" 
            :tableData="supplier.tableData" 
            :tableLabel="supplier.tableLabel" 
            :models="supplier"  
            @on-check-click="supplierCheckSelected"
            @on-search-click="supplierOpen"
            @on-cancel-click="supplier.visible=false"/>
        </el-dialog>


        <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
                <span>供应商</span>
                <div style="float: right;">
                    <el-button size="small" type="primary" @click="supplierOpen(true)">选择供应商</el-button>
                </div>
            </div>
            <el-table :data="supplierDetails.tableData" ref="table" stripe>
                <el-table-column prop="name" label="供应商名称">
                    <template slot-scope="scope">
                        <el-button type="text" @click="findSupplierDetails(scope.row)">{{scope.row.name}}</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="contactPerson" label="联系人"></el-table-column>
                <el-table-column prop="contactPhone" label="联系方式"></el-table-column>
                <el-table-column prop="wechat" label="传真"></el-table-column>
                <el-table-column label="操作" width="210">
                    <template slot-scope="scope">
                        <el-button type="danger" size="mini" @click="delSuppliers(scope.row,scope,scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--供应商基本信息-->
            <el-dialog :title="supplierDetails.title" append-to-body :visible.sync="supplierDetails.visible" :width="supplierDetails.width" :close-on-click-modal="false">
                <table class="custom-table">
                    <tr>
                        <td class="tr-title">供应商名称</td><td>{{supplierDetails.row.name}}</td>
                        <td class="tr-title">联系人</td><td>{{supplierDetails.row.contactPerson}}</td>
                    </tr>
                    <tr>
                        <td class="tr-title">联系方式</td><td>{{supplierDetails.row.contactPhone}}</td>
                        <td class="tr-title">传真</td><td>{{supplierDetails.row.wechat}}</td>
                    </tr>
                    <tr>
                        <td class="tr-title">微信</td><td>{{supplierDetails.row.fax}}</td>
                        <td class="tr-title">邮箱</td><td>{{supplierDetails.row.email}}</td>
                    </tr>
                    <tr>
                        <td class="tr-title">注册资金</td><td>{{supplierDetails.row.registeredCapital}}</td>
                        <td class="tr-title">统一社会代码</td><td>{{supplierDetails.row.licenseNo}}</td>
                    </tr>
                    <tr>
                        <td class="tr-title">成立日期</td><td>{{supplierDetails.row.buildDate}}</td>
                        <td class="tr-title">所在地址</td><td>{{supplierDetails.row.addresss}}</td>
                    </tr>
                    <tr>
                        <td class="tr-title">经营地址</td><td>{{supplierDetails.row.businessAddresss}}</td>
                        <td class="tr-title">邮编</td><td>{{supplierDetails.row.postCode}}</td>
                    </tr>
                    <tr>
                        <td class="tr-title">网址</td><td>{{supplierDetails.row.siteUrl}}</td>
                        <td class="tr-title">所属经济行业</td><td>{{supplierDetails.row.trade}}</td>
                    </tr>
                    <tr>
                        <td class="tr-title">企业规模</td><td>{{supplierDetails.row.scale}}</td>
                        <td class="tr-title">状态</td><td>{{supplierDetails.row.statusFlag=='1'?'正常':'禁用'}}</td>
                    </tr>
                    <tr>
                        <td class="tr-title">公司介绍</td><td colspan="2">{{supplierDetails.row.introduction}}</td>
                    </tr>
                    <tr>
                        <td class="tr-title">经营范围</td><td colspan="2">{{supplierDetails.row.businessScope}}</td>
                    </tr>
                    <tr>
                        <td class="tr-title">公司资质</td><td colspan="2">{{supplierDetails.row.qualification}}</td>
                    </tr>
                </table>
            </el-dialog>
        </el-card>


        <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span>采购劳务</span>
            </div>
            <el-table :data="labourTableData" style="width: 100%;" stripe>
                <el-table-column prop="name" label="劳务名称"></el-table-column>
                <el-table-column prop="applyNum" label="申请数量"></el-table-column>
                <el-table-column prop="estimatePrice" label="预估价">
                    <template slot-scope="scope">
                        {{ scope.row.estimatePrice/100}}
                    </template>
                </el-table-column>
                <el-table-column prop="purchasedNum" label="采购数量">
                    <template slot-scope="scope">
                        <el-input v-model='scope.row.purchasedNum' oninput="value=value.indexOf('.') > -1?value.slice(0, value.indexOf('.') + 3):value"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="remarks" label="备注" width="250">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.remarks" type="textarea"></el-input>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        
  
           
    </div>
</template>

<script>
    import { 
        FORM_PURCHASE_INVITATION,
        OPTION_INLINE,
        OPTION_BLOCK
    } from "@/views/labourPurchase/labourModel/purchase_form"
    import { 
        LABEL_SUPPLIER,
        LABEL_PORJECT
    } from "@/config/common"
    import projectFormList from "@/components/modules/project_form_list"
    import supplierFormList from "@/components/modules/supplier_form_list"
    import { uploads } from "@/api/common_api"
    import { getProjectList } from "@/api/project_api"
    import { getSupplierList} from "@/api/supplier_api"
    import { bidPurchaseCreate} from "@/api/labour_purchase_api"
    export default {
        components:{
            projectFormList,
            supplierFormList
        },
        props: ['row'],
        data() {
            return {
                form:{
                    fApi:{},
                    rule:FORM_PURCHASE_INVITATION,
                    option:OPTION_BLOCK
                },
                labourTableData:[],
                //临时附件储存
                annxFileName:'',
                supplier:{
                    title:'供应商',
                    width:"1200px",
                    keys:0,
                    visible:false,
                    tableData:[],
                    tableLabel: LABEL_SUPPLIER,
                    total:0
                },
                supplierDetails:{
                    title:'供应商基本信息',
                    width:"1200px",
                    visible:false,
                    tableData:[],
                    row:{}
                },
                project:{
                    title:'项目库',
                    width:"1200px",
                    hackReset:true,
                    visible:false,
                    tableData:[],
                    tableLabel: LABEL_PORJECT,
                    total:0
                },
                params: {
                    type:"page",
                    pageNum: 1,
                    pageSize: 10
                }
            };
        },
        mounted(){
            this.initData();
            //console.log(process.env.VUE_APP_FILE)
        },
        methods: { 
            //初始化数据
            initData(){
                this.form.fApi.setValue({
                    "address":"",
                    "receiverPhone":"",
                    "receiverName":"",
                    "name":"",
                    "isOpen":"",
                    "payType":"",
                    "files":"",
                    "startTime":"",
                    "endTime":"",
                    "quoteNum":"",
                    "reason":"",
                    "remarks":"",
                });
                this.annxFileName = '';//清空临时储存附件
                this.supplierDetails.tableData = [];//供应商
                this.labourTableData = [];//物资
                //判断是单个还是多个物资
                if(Array.isArray(this.row)){
                    this.form.fApi.setValue({"name":this.row[0].name});//项目名称
                    this.labourTableData = this.row;
                }else{
                    this.form.fApi.setValue({"name":this.row.name});//项目名称
                    this.labourTableData = [this.row];
                }   
            },
             //选择项目库
             async projectOpen(formData){
                let params = {};
                if(formData === true){
                    params.pageNum = 1;
                    params.pageSize = 10;
                }else{
                    params.pageNum = formData.pageNum;
                    params.pageSize = formData.pageSize;
                    params.name = formData.name;
                }
                const {code,data} = await getProjectList(params);
                if(code === 200){
                    this.project.tableData = data.list;
                    this.project.total = data.total;
                    if(formData === true){//新增的时候才打开
                        this.project.visible = true;
                    }
                }
            },
            //提交项目库
            projectCheckSelected(row){
                this.form.fApi.setValue({"receiverName":row[0].receiverName,"receiverPhone":row[0].receiverPhone,"address":row[0].address});
                this.project.visible = false;
            },
            //选择供应商
            async supplierOpen(formData){
                let params = {};
                if(formData === true){
                    params.pageNum = 1;
                    params.pageSize = 10;
                }else if(formData !== true && formData.flag){
                    params.pageNum = 1;
                    params.pageSize = 10;
                    params.name = formData.name;
                    this.supplier.keys++;
                }else{
                    params.pageNum = formData.pageNum;
                    params.pageSize = formData.pageSize;
                    params.name = formData.name;
                }
                params.productType = '2';//默认查询劳务供应商   1.物资供应商 2.劳务供应商
                params.statusFlag = '1';//审核正常的
                //params.supplierType = '0';//供应商类别 0.库内供应商 1.库外供应商
                const {code,data} = await getSupplierList(params);
                if(code === 200){
                    this.supplier.tableData = data.list;
                    this.supplier.total = data.total;
                    if(formData === true){//新增的时候才打开
                        this.supplier.keys++;
                        this.supplier.visible = true;
                    }
                }
            },
             //提交供应商
            supplierCheckSelected(selectItem){
                const idList = this.supplierDetails.tableData.map(v=>v.id);
                selectItem.forEach(v=>{
                    if(!idList.includes(v.id)){
                        this.supplierDetails.tableData.push(v);
                    }
                })
                this.supplier.visible = false;
            },
            //供应商基本信息
            findSupplierDetails(row){
                this.supplierDetails.row = row;
                this.supplierDetails.visible = true;
            },
            //删除供应商
            delSuppliers(row,index){
                this.$confirm('是否删除？', "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(async () => {
                    this.supplierDetails.tableData.splice(index,1);//删除供应商后从新渲染
                }).catch((error) => {});
            },
            //上传pdf
            uploadPdf(){
                this.$refs.pdfFile.click();
            },
            async pdfChange(e){
                e.preventDefault();
                let _this = this;
                let file = e.target.files[0];
                if(file===undefined){return;}
                let formData = new FormData();
                formData.append("resType",file);
                const {code,data} = await uploads('annxPDF',formData);
                if(code === 200){
                    this.annxFileName = data;//临时储存
                    this.form.fApi.setValue({"files":file.name});//传给后端
                    e.target.value = "";
                }
            },
            //提交
            onFormSubmit(){
                this.form.fApi.submit(async (formData, $f) => {
                try {
                    //bidGoodsDetailVOList  采购物资明细
                    //dept 部门信息
                    //project 项目信息

                    const _material = this.labourTableData;
                    for(var i=0;i<_material.length;i++){
                        if(_material[i].purchasedNum === 0 || _material[i].purchasedNum === ''){
                            return this.$message.error('物资信息第'+(i+1)+'行采购数量未填写');
                        }
                        if(_material[i].purchasedNum > _material[i].applyNum){
                            return this.$message.error('物资信息第'+(i+1)+'行采购数量大于了申请数量');
                        }
                    }
                   
                    const _supplier = this.supplierDetails.tableData;
                    if(_supplier.length ===0){
                        return this.$message.error('请选择供应商');
                    }
                     //填写的供应商数量不能大于一选择的供应商数量
                    if(_supplier.length > formData.quoteNum){
                        return this.$message.error('选择的供应商数量不能大于填写的供应商数量');
                    }
                    
                    let params = {};
                    params.bidLabourDetailVOList = this.labourTableData.map(v=>{
                        return {
                            id:v.id,
                            labourId:v.labourId,
                            name:v.name,
                            purchasedNum:v.purchasedNum,
                            remarks:v.remarks
                        }
                    });  //劳务列表
                    let totalSumAll = 0;
                    this.labourTableData.map((item) => {totalSumAll += item.purchasedNum*item.estimatePrice})
                    params.totalPrice = totalSumAll;//采购总价
                    params.address = formData.address;//地址
                    params.receiverPhone =formData.receiverPhone;//联系电话
                    params.receiverName = formData.receiverName;//联系人
                    params.files = this.annxFileName;//附件
                    let supplierIds = this.supplierDetails.tableData.map(v=>{return v.id});//供应商id
                    params.invitationSupplierIds = supplierIds.join(',');//转成字符串 已逗号隔开
                    params.name = formData.name;//项目名称
                    params.bidType = 2;
                    params.projectType = 2;//招标内容 1：物资招标 2.劳务招标
                    params.startTime = formData.startTime;//开始时间
                    params.endTime = formData.endTime;//结束时间
                    params.quoteNum = formData.quoteNum;//供应商数量
                    params.reason = formData.reason;//其他原因
                    params.remarks = formData.remarks;//备注
                    const {code,msg} = await bidPurchaseCreate(params);
                    if(code === 200){
                        this.$message.success('操作成功');
                        this.onClose();
                    }
                } catch (error) {}
                })
            },
            onClose(){
                this.$emit('on-cancel-click','invitation');
            }
        }
    };
    </script>
    
    <style>
        /*按钮*/
        .el-input__suffix{
            right: 0 !important;
        }
    </style>